#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
2019-7-19 Stone @ BlueNet
尝试HSV空间颜色识别与圆形匹配识别乒乓球。
"""
import cv2 as cv
import logging
import numpy as np

from PythonCode.proj.tools import performance_measure as pmea

logging.basicConfig(level=logging.INFO)

# H, S for color recognition is enough
# HS_TH = ((15, 20), (1, 255))  # threshold of hue and saturation
HS_LOWER = (10, 100)
HS_UPPER = (20, 255)

IMG_SIZE = np.asarray((800, 800))  # the size of final image used to find the ball
R_RANGE = (IMG_SIZE[0]/4, IMG_SIZE[0]/2)  # the range of circle's radius

PTH_IMG1 = r'D:\AAA_BlueNet\BluePingPong\pingpong2.jpg'
PTH_SHAPE = r'shape_circle.png'

img_raw = cv.imread(PTH_IMG1)

counter = pmea.TimeCounter()
counter.start()

img_hsv = cv.cvtColor(img_raw, cv.COLOR_BGR2HSV)
img_hs = img_hsv[:, :, :2]  # 2 channel img with hue and saturation

logging.info("color conversion used: %s" % str(counter.get_delta_count()))

# -----------------
# COLOR RECOGNITION
# -----------------
img_wb = cv.bitwise_and(
    cv.inRange(img_hs[:,:,0], HS_LOWER[0], HS_UPPER[0]),
    cv.inRange(img_hs[:,:,1], HS_LOWER[1], HS_UPPER[1])
)

# plt.subplot(131), plt.imshow(cv.inRange(img_hs[:,:,0], HS_LOWER[0], HS_UPPER[0]), vmax=1)
# plt.subplot(132), plt.imshow(cv.inRange(img_hs[:,:,1], HS_LOWER[1], HS_UPPER[1]), vmax=1)
# plt.subplot(133), plt.imshow(img_wb, vmax=1)

logging.info("color recog used: %s" % str(counter.get_delta_count()))


# -----------------
# SHAPE RECOGNITION
# -----------------
img_circle = cv.imread(PTH_SHAPE, cv.IMREAD_GRAYSCALE)
_, cnt_cir, _ = cv.findContours(img_circle, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
_, cnt_tar, _ = cv.findContours(img_wb, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)  # tar: target

cv.drawContours(img_raw, cnt_tar, -1, (0,0,255), 1)
match_result = [cv.matchShapes(cnt_cir[0], cnt, cv.CONTOURS_MATCH_I1, 0) for cnt in cnt_tar]
match_result = np.asarray(match_result)

logging.info("findContours and shape recog used: %s" % str(counter.get_delta_count()))


str_result = ["{:<.6f}".format(x) for x in match_result]


# draw the contour most similar to circle
idx = np.where(match_result==match_result.min())
for i in idx[0]:
    cv.drawContours(img_raw, cnt_tar, i, (255, 0, 0), 3)
    (x, y), radius = cv.minEnclosingCircle(cnt_tar[i])
    cv.circle(img_raw, (int(x), int(y)), int(radius), (0,0,255), 3)
# find and draw minimum enclosing circle

# cv.imshow("", img_raw)

